package com.zzh.demo.core.utils;

import com.zzh.demo.core.enumeration.ErrorEnums;
import com.zzh.demo.core.exception.BusinessException;
import org.apache.commons.lang.StringUtils;

import java.util.Optional;

/**
 * description: 参数检查工具类<br>
 * createTime: 2019/2/1414:41 <br>
 *
 * @author zzh
 */
public class ParamCheckUtil {

    private ParamCheckUtil(){}

    /**
     *
     * Method Name：checkRequired
     * Method Description: 检查必传参数是否为空，String类型还检查是不是全是空白符<br>
     *
     * @param   value   待检查参数值
     * @param   name    参数名称
     * @throws  BusinessException
     * <p>creator：zhihui.zhou
     * <p>createTime：2019/2/14 15:05
     */
    public static void checkRequired(Object value, String name) {
        if(value == null) {
            throw new BusinessException(ErrorEnums.PARAM_REQUIRED, name);
        }
        if(value instanceof String && StringUtils.isEmpty((String) value)) {
            throw new BusinessException(ErrorEnums.PARAM_REQUIRED);
        }
    }

    /**
     *
     * Method Name：checkLength
     * Method Description: 检查字符串长度，最小值和最大值传负值，则校验直接通过<br>
     *
     * @param   value       待检查参数值
     * @param   minLegnth   参数值最小长度
     * @param   maxLength   参数值最大长度
     * @param   name        参数名称
     * @throw   BusinessException
     * <p>creator：zhihui.zhou
     * <p>createTime：2019/2/14 15:07
     */
    public static void checkStringLength(String value, Integer minLegnth, Integer maxLength, String name) {
        Integer max = Optional.ofNullable(maxLength)
                .map(l -> l>=0 ? l : Integer.MAX_VALUE)
                .orElse(Integer.MAX_VALUE);
        Integer min = Optional.ofNullable(minLegnth)
                .map(l -> l)
                .orElse(0);
        if(value instanceof String && StringUtils.isEmpty((String) value)) {
            throw new BusinessException(ErrorEnums.PARAM_REQUIRED);
        }
    }

    /**
     *
     * Method Name：checkStringPattern
     * Method Description: 检查参数值是否符合给定正则表达式<br>
     *
     * @param   value       待检查参数值
     * @param   pattern     正则表达式
     * @param   message     提示信息
     * @throw   BusinessException
     * <p>creator：zhihui.zhou
     * <p>createTime：2019/2/14 15:18
     */
    public static void checkStringPattern(String value, String pattern, String message) {
        if(!value.matches(pattern)) {
            throw new BusinessException(ErrorEnums.PARAM_PATTERN_INVALID);
        }
    }
}
